package com.xhs.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhs.dto.*;
import com.xhs.model.SearchTask;
import com.xhs.model.User;
import com.xhs.manager.SearchTaskManager;
import com.xhs.manager.UserManager;
import com.xhs.service.TaskExecutionService;
import com.xhs.service.TaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 任务管理控制器
 *
 * @author xhs
 */
@Slf4j
@RestController
@RequestMapping("/api/task")
@Tag(name = "任务管理", description = "搜索任务管理相关接口")
public class TaskController {

    @Autowired
    private SearchTaskManager searchTaskManager;

    @Autowired
    private UserManager userManager;

    @Autowired
    private TaskExecutionService taskExecutionService;

    @Autowired
    private TaskService taskService;

    /**
     * 分页获取任务列表
     */
    @Operation(summary = "分页获取任务列表", description = "分页获取当前用户的任务列表")
    @PostMapping("/list")
    public XhsResponse<IPage<SearchTask>> getTaskPage(@Valid @RequestBody TaskListRequest request) {
        log.info("分页获取任务列表请求: phoneNumber={}, pageNum={}, pageSize={}",
                request.getPhoneNumber(), request.getPageNum(), request.getPageSize());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        IPage<SearchTask> taskPage = searchTaskManager.findByUserIdWithPage(
                user.getId(), request.getPageNum(), request.getPageSize());
        return XhsResponse.success("获取任务列表成功", taskPage);
    }

    /**
     * 获取简单任务列表（只包含ID和名称）
     */
    @Operation(summary = "获取简单任务列表", description = "获取用户的任务ID和名称列表，用于下拉选择")
    @PostMapping("/simple-list")
    public XhsResponse<List<TaskListResponse>> getSimpleTaskList(@Valid @RequestBody TasksRequest request) {
        log.info("获取简单任务列表请求: phoneNumber={}", request.getPhoneNumber());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        List<TaskListResponse> taskList = searchTaskManager.getTaskListByUserId(user.getId());
        return XhsResponse.success("获取任务列表成功", taskList);
    }

    /**
     * 创建任务
     */
    @Operation(summary = "创建任务", description = "创建一个新的搜索任务")
    @PostMapping("/create")
    public XhsResponse<Long> createTask(@Valid @RequestBody CreateTaskRequest request) {
        log.info("创建任务请求: phoneNumber={}, taskName={}, keywords={}, executeInterval={}, postTimeLimit={}, searchPages={}",
                request.getPhoneNumber(), request.getTaskName(), request.getKeywords(),
                request.getExecuteInterval(), request.getPostTimeLimit(), request.getSearchPages());

        Long taskId = taskService.createTask(request.getPhoneNumber(), request.getTaskName(), 
                request.getKeywords(), request.getExecuteInterval(), request.getPostTimeLimit(), request.getSearchPages());
        if (taskId != null) {
            return XhsResponse.success("任务创建成功", taskId);
        } else {
            return XhsResponse.error("任务创建失败");
        }
    }

    /**
     * 立即执行任务
     */
    @Operation(summary = "立即执行任务", description = "立即执行指定的搜索任务")
    @PostMapping("/execute")
    public XhsResponse<String> executeTask(@Valid @RequestBody TaskExecuteRequest request) {
        log.info("立即执行任务请求: phoneNumber={}, taskId={}", request.getPhoneNumber(), request.getTaskId());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        // 查询任务
        SearchTask task = searchTaskManager.getById(request.getTaskId());
        if (task == null) {
            return XhsResponse.error("任务不存在");
        }

        // 检查任务是否属于当前用户
        if (!task.getUserId().equals(user.getId())) {
            return XhsResponse.error("无权限操作此任务");
        }

        // 异步执行任务
        taskExecutionService.executeTaskImmediately(task.getId());

        return XhsResponse.success("任务开始执行", "任务ID: " + task.getId());
    }

    /**
     * 更新任务状态
     */
    @Operation(summary = "更新任务状态", description = "更新任务的启用/禁用状态")
    @PostMapping("/update-status")
    public XhsResponse<String> updateTaskStatus(@Valid @RequestBody TaskStatusRequest request) {
        log.info("更新任务状态请求: phoneNumber={}, taskId={}, enabled={}",
                request.getPhoneNumber(), request.getTaskId(), request.getEnabled());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        // 查询任务
        SearchTask task = searchTaskManager.getById(request.getTaskId());
        if (task == null) {
            return XhsResponse.error("任务不存在");
        }

        // 检查任务是否属于当前用户
        if (!task.getUserId().equals(user.getId())) {
            return XhsResponse.error("无权限操作此任务");
        }

        // 更新任务状态
        task.setEnabled(request.getEnabled());
        boolean success = searchTaskManager.updateById(task);

        if (success) {
            return XhsResponse.success("任务状态更新成功", request.getEnabled() == 1 ? "已启用" : "已禁用");
        } else {
            return XhsResponse.error("任务状态更新失败");
        }
    }

    /**
     * 更新任务信息
     */
    @Operation(summary = "更新任务信息", description = "更新任务的名称和关键词")
    @PostMapping("/update")
    public XhsResponse<String> updateTask(@Valid @RequestBody TaskUpdateRequest request) {
        log.info("更新任务请求: phoneNumber={}, taskId={}, keywords={}, executeInterval={}, postTimeLimit={}, searchPages={}",
                request.getPhoneNumber(), request.getTaskId(), request.getKeywords(),
                request.getExecuteInterval(), request.getPostTimeLimit(), request.getSearchPages());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        // 查询任务
        SearchTask task = searchTaskManager.getById(request.getTaskId());
        if (task == null) {
            return XhsResponse.error("任务不存在");
        }

        // 检查任务是否属于当前用户
        if (!task.getUserId().equals(user.getId())) {
            return XhsResponse.error("无权限操作此任务");
        }

        // 更新任务信息
        boolean success = taskService.updateTask(request.getTaskId(), request.getKeywords(), 
                request.getExecuteInterval(), request.getPostTimeLimit(), request.getSearchPages());

        if (success) {
            return XhsResponse.success("任务更新成功", "任务ID: " + request.getTaskId());
        } else {
            return XhsResponse.error("任务更新失败");
        }
    }

    /**
     * 删除任务
     */
    @Operation(summary = "删除任务", description = "物理删除指定任务及其相关数据")
    @PostMapping("/delete")
    public XhsResponse<String> deleteTask(@Valid @RequestBody DeleteTaskRequest request) {
        log.info("删除任务请求: phoneNumber={}, taskId={}", request.getPhoneNumber(), request.getTaskId());
        
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }
        
        SearchTask task = searchTaskManager.getById(Long.valueOf(request.getTaskId()));
        if (task == null) {
            return XhsResponse.error("任务不存在");
        }
        
        if (!task.getUserId().equals(user.getId())) {
            return XhsResponse.error("无权限删除此任务");
        }
        
        try {
            searchTaskManager.deleteTask(Long.valueOf(request.getTaskId()), user.getId());
            return XhsResponse.success("任务删除成功", "任务ID: " + request.getTaskId());
        } catch (Exception e) {
            log.error("删除任务失败", e);
            return XhsResponse.error("删除任务失败: " + e.getMessage());
        }
    }


} 